package com.qianfeng.rencai.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qianfeng.rencai.dto.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by wenka on 2022/3/30 22:31
 *
 * @author wenkaixin
 * @version 1.0
 * @since 1.0
 */
@Component
@Slf4j
public class RchAuthenticationFailureHandler implements AuthenticationFailureHandler {

    private ObjectMapper objectMapper;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
//        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        response.setContentType("application/json;charset-UTF-8");
        R result = R.setOK(exception.getMessage());
        if (exception instanceof BadCredentialsException) {
            result = R.setOK("账户名或密码错误");
        }
        String json = objectMapper.writeValueAsString(result);
        response.getWriter().write(json);
    }
}
